package com.liachen.stock.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liachen.common.enums.UserType;
import com.liachen.stock.controller.req.QueryStockSummaryReq;
import com.liachen.stock.entity.StockSimple;
import com.liachen.stock.service.IUserService;
import com.liachen.stock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/stock")
@Slf4j
public class StockController {
    @Autowired
    private StockService stockService;
    @Autowired
    private IUserService userService;

    /**
     * 从同花顺拉取数据
     * @param type
     * @return
     */
    @RequestMapping("/get-info-from-ths")
    public String getInfoFromThs() {
        for (UserType userType : UserType.values()) {
            log.info("拉取数据开始, type={}", userType.name());
            stockService.saveStockInfo(userType.name());
            log.info("拉取数据结束, type={}", userType.name());
        }
        return "success";
    }

    /**
     * 导出股票统计
     * @param fileName
     * @param num
     * @param response
     */
    @RequestMapping("/export-stock-summary-info")
    public void exportStockSummaryInfo(String fileName, QueryStockSummaryReq req, HttpServletResponse response) {
        stockService.exportStockSummaryInfo(fileName, req, response);
    }

    /**
     * 导出股票统计
     * @param fileName
     * @param num
     * @param response
     */
    @RequestMapping("/export-all-stock-summary")
    public void exportAllStockSummary(String fileName, Integer num, HttpServletResponse response) {
        stockService.exportAllStockSummary(fileName, num, response);
    }

    /**
     * 导入股票统计
     * @param fileName
     * @param num
     * @param response
     */
    @RequestMapping("/query-stock-today-info")
    public void queryStockTodayInfo(@RequestParam MultipartFile file, HttpServletResponse response) {
        stockService.queryStockTodayInfo(file, response);
    }



    /**
     * 查询空仓数量
     * @param noStock
     */
    @RequestMapping("/count-stock")
    public Integer countStock(Integer noStock) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (Objects.nonNull(noStock)) {
            queryWrapper.eq("no_stock", noStock);
        }
        queryWrapper.apply("modify_time > DATE({0}) AND modify_time <= DATE_ADD({0}, INTERVAL 1 DAY)", DateUtil.beginOfDay(new Date()).toJdkDate());
        return userService.count(queryWrapper);
    }
}
